package cn.virens.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.virens.common.exception.APIException;
import cn.virens.common.exception.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

public class AesUtil {
    private static final Charset charset = Charset.forName("UTF-8");
    private static final Logger logger = LoggerFactory.getLogger(AesUtil.class);

    /**
     * 对String字符串进行MD5加密
     *
     * @param string 原始字符串
     * @return MD5_HEX
     * @throws APIException 异常抛出
     */
    public static String md5(String string) throws APIException {
        if (string != null && !string.isEmpty()) {
            return DigestUtil.md5Hex(string);
        } else {
            return null;
        }
    }

    /**
     * AES解密
     *
     * @param value 待解密的内容
     * @param key   密钥
     * @return 返回解密内容
     * @throws APIException 异常包装
     */
    public static String decrypt(String value, String key) throws APIException {
        return ExceptionUtil.safe1(logger, () -> aes(key).decryptStr(value));
    }

    /**
     * AES加密
     *
     * @param value 待加密的内容
     * @param key   密钥
     * @return 返回加密内容
     * @throws APIException 异常包装
     */
    public static String encrypt(String value, String key) throws APIException {
        return ExceptionUtil.safe1(logger, () -> aes(key).encryptBase64(value));
    }

    private static AES aes(String key) throws APIException {
        return SecureUtil.aes(StrUtil.bytes(key, charset));
    }
}
